<template>
  <div class="user-edit">
    <Drawer :title="title" v-model="visible" width="1024" :mask-closable="false">
      <Scroll :height="height">
        <Form  ref="contractForm" :model="contractForm" :label-width="120" :rules="contractFormValidate">
          <Row :gutter="64" type="flex" justify="start">
            <Col span="11">
              <FormItem label="项目名称" prop="project_id" v-show="type=='1'">
                <Select v-model="contractForm.project_id" clearable filterable @on-change="getContractName">
                  <Option v-for="item in projectName" :value="item.id" :key="item.id">{{ item.project_name }}</Option>
                </Select>
              </FormItem>
            </Col>
            <Col span="11">
              <FormItem label="合同编号" prop="contract_code">
                <Input v-model="contractForm.contract_code" placeholder="请输入合同编号"/>
              </FormItem>
            </Col>
          </Row>
          <Row :gutter="64" type="flex" justify="start">
            <Col span="11">
              <FormItem label="合同名称" prop="contract_name" >
                <Input v-model="contractForm.contract_name" placeholder="请输入合同名称"/>
              </FormItem>
            </Col>
            <Col span="12">
              <FormItem label="签订日期" prop="contract_date">
                <DatePicker :value="contractForm.contract_date" type="date"
                  placeholder="请选择日期"
                  @on-change="getContractDate"
                  style="width: 280px"></DatePicker>
              </FormItem>
            </Col>
          </Row>
          <Row :gutter="64" type="flex" justify="start">
            <Col span="11">
              <FormItem label="合同价款" prop="cost" >
                <Input v-model="contractForm.cost" placeholder="请输入合同价款"/>
              </FormItem>
            </Col>
            <Col span="12">
              <FormItem label="税率及发票类型" prop="tax">
                <Input v-model="contractForm.tax_race" style="width: 40px;"/>%税率的
                <Select v-model="contractForm.ticket_type" clearable filterable style="width: 150px;">
                  <Option v-for="item in ticketType" :value="item.name_id" :key="item.id">{{ item.name }}</Option>
                </Select>
              </FormItem>
            </Col>
          </Row>
          <Row :gutter="64" type="flex" justify="start">
            <Col span="11">
              <FormItem label="甲方名称" prop="part_a">
                {{ partAName.name }}
              </FormItem>
            </Col>
            <Col span="11">
              <FormItem label="甲方银行帐户" prop="part_a_account">
                <Select v-model="contractForm.part_a_account" clearable filterable style="width: 360px;">
                  <Option v-for="item in partABankAccount" :value="item.id" :key="item.id">{{ item.bank_name }}</Option>
                </Select>
              </FormItem>
            </Col>
          </Row>
          <Row :gutter="64" type="flex" justify="start">
            <Col span="11">
              <FormItem label="乙方名称" prop="part_b">
                <Select v-model="contractForm.part_b" clearable filterable @on-change="getPartBAccount">
                <Option v-for="item in partBList" :value="item.id" :key="item.id">{{ item.company }}</Option>
              </Select>
              </FormItem>
            </Col>
            <Col span="11">
              <FormItem label="乙方银行帐户" prop="part_b_account">
                <Select v-model="contractForm.part_b_account" clearable filterable style="width: 360px;">
                  <Option v-for="item in partBBankAccount" :value="item.id" :key="item.id">{{ item.bank_name }}</Option>
                </Select>
              </FormItem>
            </Col>
          </Row>
        </Form>
        <Row v-show="type=='2'">
          <Col span="22" offset="1">
            <div><b>标的，数量及价款</b></div>
            <table class="gridtable">
              <tr>
                <th>序号</th>
                <th>物料名称</th>
                <th>规格型号</th>
                <th>单位</th>
                <th>单价</th>
                <th>数量</th>
                <th>金额</th>
                <th>操作</th>
              </tr>
              <tr v-for="(item, index) in contractForm.detail" :key="index">
                <td style="text-align: center">{{index + 1}}<i style="display: none">{{item.id}}</i></td>
                <td>{{item.name}}</td>
                <td>{{item.stype}}</td>
                <td style="text-align: center">{{item.unit}}</td>
                <td style="text-align: right">{{item.price}}</td>
                <td style="text-align: center;width: 100px">
                  <Button size="small" type="primary" @click="handle_sub(index)">-</Button>
                  <input type="text" v-model="item.count" style="width: 40px;text-align: center;" readonly="readonly">
                  <Button size="small" type="primary" @click="handle_add(index)">+</Button>
                </td>
                <td style="text-align: right">{{(item.price * item.count).toFixed(2)}}</td>
                <td style="text-align: center;width: 100px">
                  <Button size="small" type="primary" @click="handle_edit_material(index)">编辑</Button>
                  <Button size="small" type="error" @click="handle_del(index)">删除</Button>
                </td>
              </tr>
              <tr>
                <td style="text-align: center">#</td>
                <td style="text-align: center">合计</td>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
                <td style="text-align: right" v-if="type=='2'">{{ sum.toFixed(2) }}</td>
                <td></td>
            </tr>
            </table>
          </Col>
          
        </Row>
        <Row v-show="type=='2'">
          <Col span="22" offset="2" style="margin-top: 16px;">
            <Button type="primary" @click="addMaterial" icon="md-add">新增</Button>
          </Col>
        </Row>
      </Scroll>
      <div class="demo-drawer-footer">
        <Button @click="handleCancel" style="margin-right: 36px;">取消</Button>
        <Button type="primary" :loading="submitLoading" @click="submit">确定</Button>
      </div>
    </Drawer>
    <Modal :title="subTitle" v-model="addEditVisiable" :mask-closable='false' :width="500" :styles="{top: '400px', left: '200px'}" @on-ok="handle_ok">
      <Form ref="sysMaterialForm" :model="sysMaterialForm" :label-width="100">
        <FormItem label="物料名称" prop="sysMaterialForm.material_name" class="margin-bottom-3">
          <Select v-model="sysMaterialForm.material_name" clearable filterable style="width:320px" @on-change="changeMaterialName">
            <Option v-for="(item,index) in materialClass" :value="item.pre_code" :key="index">
              {{item.name}}
            </Option>
          </Select>
        </FormItem>
        <FormItem label="规格型号" prop="sysMaterialForm.material_type" class="margin-bottom-3">
          <Select v-model="sysMaterialForm.material_type" clearable filterable style="width:320px">
            <Option v-for="(item,index) in materialType" :value="item.id" :key="index">
              {{item.stype}}
            </Option>
          </Select>
        </FormItem>
        <FormItem label="含税单价" prop="sysMaterialForm.price" class="margin-bottom-3">
          <InputNumber v-model="sysMaterialForm.price" style="width: 320px" />
        </FormItem>
        <FormItem label="数量" prop="sysMaterialForm.count" class="margin-bottom-3">
          <InputNumber v-model="sysMaterialForm.count" style="width: 320px" />
        </FormItem>
      </Form>
    </Modal>
  </div>
</template>
<script>
import { getProject } from '@/api/project';
import { getContractType, getBankAccount, getPartB, getSupplierName, insertSupplierContract, updateSupplierContract, 
         updateSupplierContractDetail, insertSupplierContracrtDetail, getSupplierContracrtDetail, deleteSupplierContracrtDetail,
         updateSupplierContracrtDetail, updateSupplierContracrtDetailById } from '@/api/contract';
import { getAllMaterialName, getAllMaterials } from '@/api/typical';
import moment from 'moment';
export default {
  name: 'add-edit-supplier-contract',
  props: {
    value: {
      type: Boolean,
      default: false
    },
    data: {
      type: Object
    },
    type: {
      /**
       * '2': 编辑项目合同
       * '1': 添加项目合同
       */
      type: String,
      default: "0"
    }
  },
  data() {
    const validateAccount = (rule, value, callback) => {
      if (!value) {
        callback(new Error('银行账号必须选择'))
      } else {
        callback();
      }
    };
    const validateName = (rule, value, callback) => {
      if (!value) {
        callback(new Error('公司名称必须选择'))
      } else {
        callback();
      }
    };
    return {
      visible: this.value,
      title: "",
      height: 540,
      submitLoading: false,
      projectName: [],
      ticketType: [],
      partBList: [],
      partBBankAccount: [],
      partAName: {},
      partABankAccount: [],
      contractForm: {},
      contractFormValidate: {
        part_b: [
          {validator: validateName, trigger: "blur"}
        ],
        part_a_account: [
          {validator: validateAccount, trigger: "blur"}
        ],
        part_b_account: [
          {validator: validateAccount, trigger: "blur"}
        ],
        contract_code: [
          {required: true, message: "合同编号不能为空", trigger: "blur"}
        ],
        contract_name: [
          {required: true, message: "合同名称不能为空", trigger: "blur"}
        ],
        project_content: [
          {required: true, message: "工程概况不能为空", trigger: "blur"}
        ],
        cost: [
          {required: true, message: "合同价款不能为空", trigger: "blur"}
        ]
      },
      addEditVisiable: false,
      subTitle: '',
      insertOrEdit: true,
      sysMaterialForm: {
        id: 0,
        material_name: '',
        material_type: 0,
        price: 0,
        count: 1
      },
      materialClass: [],
      materialLib: [],
      materialType: [],
    }
  },
  methods: {
    getProjectName() {
      getProject().then(res => {
        if (res.code === 0) {
          this.projectName = res.data;
        }
      })
    },
    getContractName(v) {
      this.contractForm.contract_name = this.projectName.filter(item => item.id === v)[0].project_name + '物资采购合同';
      this.contractForm.tax_race = 13;
      this.contractForm.ticket_type = 1;
      this.contractForm.contract_date = moment(new Date()).format('YYYY-MM-DD');
    },
    getContractDate(v) {
      this.contractForm.contract_date = v;
    },
    getContractAward() {
      getContractType({type: 12}).then(res => {
        if (res.code === 0) {
          this.ticketType = res.data;
        }
      })
    },
    getPartAName() {
      getPartB().then(res => {
        if (res.code === 0) {
          this.partAName = res.data;
        }
      });
    },
    getPartABankAccount() {
      const params = {
        company_type: 4,
        company_id: 1
      };
      getBankAccount(params).then(res => {
        if (res.code === 0) {
          this.partABankAccount = res.data;
        }
      })
    },
    getPartBName() {
      getSupplierName({type: 26}).then(res => {
        if (res.code === 0) {
          this.partBList = res.data;
        }
      });
    },
    getPartBAccount(v) {
      this.getPartBBankAccount(v);
    },
    getPartBBankAccount(company_id) {
      const params = {
        company_type: 2,
        company_id
      }
      getBankAccount(params).then(res => {
        if (res.code === 0) {
          this.partBBankAccount = res.data;
        }
      })
    },
    init() {
      this.getProjectName();
      this.getContractAward();
      this.getPartAName();
      this.getPartABankAccount();
      this.getPartBName();
      this.getMaterialInfo();
      switch(this.type) {
        case '1':
          this.title = '新增物资采购合同';
          this.contractForm = {};
          break;
        case '2':
          this.title = '编辑物资采购合同';
          this.contractForm = this.data;

          this.getPartBAccount(this.contractForm.part_b);
          break;
      }
    },
    handleCancel() {
      this.visible = false;
    },
    submit() {
      this.$refs.contractForm.validate(valid => {
        if (valid) {
          switch(this.type) {
            case '1':   // 新增
              this.submitLoading = true;
              this.contractForm.part_a = this.partAName.id;
              insertSupplierContract(this.contractForm).then(res => {
                this.submitLoading = false;
                if (res.code === 0) {
                  this.$Message.success(res.message);
                  this.$emit("on-submit", true);
                  this.visible = false;
                }
              })
              break;
            case '2':
              this.submitLoading = true;
              updateSupplierContract(this.contractForm).then(res => {
                this.submitLoading = false;
                if (res.code === 0) {
                  this.$Message.success(res.message);
                  const params = {
                    supplier_contract_id: this.contractForm.id,
                    supplier_id: this.contractForm.part_b
                  };
                  console.log('params', params)
                  updateSupplierContracrtDetailById(params);
                  this.$emit("on-submit", true);
                  this.visible = false;
                }
              })
              break;
          }
        }
      })
    },
    setCurrentValue(value) {
      this.visible = value;
    },
    handle_sub(index) {
      if (this.contractForm.detail[index].count == 1) {
        return false;
      } else {
        this.contractForm.detail[index].count--;
      }
      this.change_count(index);
    },
    handle_add(index) {
      this.contractForm.detail[index].count++;
      this.change_count(index);
    },
    change_count(index) {
      const id = this.contractForm.detail[index].id;
      const count = this.contractForm.detail[index].count;
      updateSupplierContractDetail({id, count}).then(res => {
        if (res.code === 0) {
          this.$Message.success(res.message);
        }
      })
    },
    getMaterialInfo() {
      // 获取所有的物料名称
      getAllMaterialName().then(res => {
        if (res.code === 0) {
          this.materialClass = res.data.raws;
        }
      });
      // 获取所有的物料
      getAllMaterials().then(res => {
        if (res.code === 0) {
          this.materialLib = res.data.rows;
        }
      })
    },
    changeMaterialName(value) {
      this.materialType = this.materialLib.filter(item => item.base_code == value);
    },
    handle_del(index) {
      this.$Modal.confirm({
        title: '确定删除',
        content: '确定要删除这条记录吗？',
        onOk: () => {
          const id = this.contractForm.detail[index].id;
          deleteSupplierContracrtDetail({id}).then(res => {
            if (res.code === 0) {
              this.contractForm.detail.splice(index, 1);
              this.$Message.info(res.message);
            }
          })
        }
      });
    },
    handle_edit_material(index) {
      this.subTitle = '编辑物料';
      this.insertOrEdit = false;
      this.sysMaterialForm.id = this.contractForm.detail[index].id;
      this.sysMaterialForm.material_name = this.contractForm.detail[index].code.substring(0, 6);
      this.sysMaterialForm.material_type = this.contractForm.detail[index].material_id;
      this.sysMaterialForm.price = this.contractForm.detail[index].price;
      this.materialType = this.materialLib.filter(item => item.base_code == this.sysMaterialForm.material_name);
      this.sysMaterialForm.count = this.contractForm.detail[index].count;
      this.addEditVisiable = true;
    },
    addMaterial() {
      this.subTitle = '新增物料';
      this.insertOrEdit = true;
      this.addEditVisiable = true;
    },
    handle_ok() {
      let params = {
        supplier_contract_id: this.contractForm.id,
        material_id: this.sysMaterialForm.material_type,
        count: this.sysMaterialForm.count,
        price: this.sysMaterialForm.price,
        supplier_id: this.contractForm.part_b
      };
      if (this.insertOrEdit) {
        if (this.sysMaterialForm.material_type > 0) {
          insertSupplierContracrtDetail(params).then(res => {
            if (res.code === 0) {
              this.$Message.success(res.message);
              const params = {supplier_contract_id: this.contractForm.id};
              getSupplierContracrtDetail(params).then(res => {
                if (res.code === 0) {
                  this.contractForm.detail = res.data;
                  this.addEditVisiable = false;
                }
              })
            }
          });
        }
      } else {
        if (this.sysMaterialForm.material_type > 0) {
          params.id = this.sysMaterialForm.id;
          updateSupplierContracrtDetail(params).then(res => {
            if (res.code === 0) {
              this.$Message.success(res.message);
              const params = {supplier_contract_id: this.contractForm.id};
              getSupplierContracrtDetail(params).then(res => {
                if (res.code === 0) {
                  this.contractForm.detail = res.data;
                  this.addEditVisiable = false;
                }
              })
            }
          });
        }
      }
    }
  },
  watch: {
    value(val) {
      this.setCurrentValue(val);
    },
    visible(value) {
      this.init();
      this.$emit("input", value);
    }
  },
  computed: {
    sum() {
      let sum = 0;
      this.contractForm.detail.forEach(item => {
        sum += item.count * item.price;
      });
      return sum;
      // this.contractForm.detail.reduce(item => {
      //   return item.count * item.price
      // })
    }
  },
  mounted() {
    this.height = Number(document.documentElement.clientHeight - 120);
    this.init();
  }
}
</script>
<style lang="less" scoped>
.demo-drawer-footer{
  width: 100%;
  position: absolute;
  bottom: 0;
  left: 0;
  border-top: 1px solid #e8e8e8;
  padding: 10px 16px;
  text-align: right;
  background: #fff;
}
.gridtable {
  font-family: verdana, arial, sans-serif;
  font-size: 12px;
  color: #000000;
  border-width: 1px;
  border-color: #777777;
  border-collapse: collapse;
  width: 100%;
}

.gridtable th {
  border-width: 1px;
  padding: 6px;
  border-style: solid;
  border-color: #aaaaaa;
  background-color: #dedede;
}

.gridtable td {
  border-width: 1px;
  padding: 4px;
  border-style: solid;
  border-color: #8b8b8b;
  background-color: #ffffff;
  
}
</style>
